package com.mzj.saas.mservice.sys.service;

import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.enums.OSSUploadFileTypeEnum;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.department.vo.DepartmentVO;
import com.mzj.saas.mservice.oss.service.OSSService;
import com.mzj.saas.mservice.params.entity.SystemParam;
import com.mzj.saas.mservice.params.service.SystemParamService;
import com.mzj.saas.mservice.sys.entity.*;
import com.mzj.saas.mservice.sys.repository.*;
import com.mzj.saas.mservice.sys.vo.CompanyAreaTimeZoneVO;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;


@Service
public class CompanyMessageService {
    private Logger LOG = LoggerFactory.getLogger(CompanyMessageService.class);
    @Autowired
    private RedisService redisService;
    @Autowired
    private OSSService ossService;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private PermissionRepository permissionRepository;
    @Autowired
    private GlobalAreaRepository globalAreaRepository;
    @Autowired
    private GlobalTimeZoneRepository globalTimeZoneRepository;
    @Autowired
    private DepartmentAreaRepository departmentAreaRepository;
    @Autowired
    private DepartmentTimeZoneRepository departmentTimeZoneRepository;
    @Autowired
    private SystemParamService systemParamService;
    /**
     * OSS 域名
     */
    @Value("${ali.oss.endpoint}")
    private String endpoint;
    /*
     *oss地址
     */
    @Value("${ali.oss.bucket}")
    private String bucket;

    /*
     *企业设置
     */
    @Transactional
    public ResultBean<Object> companySet(String accessToken, DepartmentVO departmentVO, MultipartFile file) {
        LOG.info("CompanyMessageService companySet accessToken={},departmentVO={}", accessToken, departmentVO);
        ResultBean<Object> resultBean = new ResultBean<>();
        resultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        resultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        resultBean.setResultData(Collections.emptyList());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return resultBean;
            }
            Optional<Department> existCompanyOptional = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existCompanyOptional == null) {
                return ResultBean.failedResultWithMsg("企业信息不存在或已删除");
            }
            if (departmentVO == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                resultBean.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                return resultBean;
            }
            if (StringUtils.isBlank(departmentVO.getName())) {
                return ResultBean.failedResultWithMsg("企业名称不能为空");
            }
            Department department = existCompanyOptional.get();
            if (file != null) {
                ResultBean<Object> objectResultBean = ossService.putFile(bucket, file, OSSUploadFileTypeEnum.AD.toString());
                String picUrl = String.valueOf(objectResultBean.getResultData());
                //String icon = ossService.getOssFilePath(picUrl);
                departmentVO.setIcon(picUrl);
                //删除原始oss图片
                if (!StringUtils.isBlank(department.getIcon())) {
                    String path = department.getIcon();
                    path = path.replaceAll(endpoint + "/", "");
                    path = path.split("\\?")[0];
                    ossService.deleteObject(bucket, path);
                }
            }
            if (!StringUtils.isBlank(departmentVO.getIcon())) {
                department.setIcon(departmentVO.getIcon());
            }
            department.setName(departmentVO.getName());
            department.setDecription(departmentVO.getDecription());
            departmentRepository.save(department);
        } catch (Exception e) {
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(e.getMessage());
        }
        return resultBean;
    }

    /*
     *显示企业信息
     */
    public ResultBean<Object> findCompanyInfo(String accessToken) {
        LOG.info("CompanyMessageService findCompanyInfo accessToken={}", accessToken);
        ResultBean<Object> result = new ResultBean<>();
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            Optional<Department> existCompanyOptional = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existCompanyOptional == null) {
                return ResultBean.failedResultWithMsg("企业信息不存在或已删除");
            }
            Department department = existCompanyOptional.get();
            result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
            result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
            result.setResultData(department);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *公租房公示设置
     */
    public ResultBean<Object> setPassPublicHousePermission(String accessToken, Long permissionId) {
        LOG.info("CompanyMessageService setPassPublicHousePermission accessToken={}", accessToken);
        ResultBean<Object> result = new ResultBean<>();
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            Optional<Department> existCompanyOptional = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existCompanyOptional == null) {
                return ResultBean.failedResultWithMsg("企业信息不存在或已删除");
            }
            Optional<Permission> existPermission = permissionRepository.findById(permissionId);
            if (existPermission == null) {
                return ResultBean.failedResultWithMsg("该权限信息不存在或已删除");
            }
            Permission permission = existPermission.get();

            Department department = existCompanyOptional.get();
            result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
            result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
            result.setResultData(department);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *地区列表显示
     */
    public ResultBean<Object> globalAreaList(String accessToken) {
        LOG.info("CompanyMessageService globalAreaList accessToken={}", accessToken);
        ResultBean<Object> result = new ResultBean<>();
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            Optional<Department> existCompanyOptional = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existCompanyOptional == null) {
                return ResultBean.failedResultWithMsg("企业信息不存在或已删除");
            }
            Iterable<GlobalArea> globalAreas = globalAreaRepository.findAll();

            List<GlobalArea> data=new ArrayList<>();
            List<GlobalArea> tempList=new ArrayList<>();

            for(GlobalArea area : globalAreas){
                if(area.getName().contains("中国")){
                    if(area.getName().equals("中国")){
                        data.add(0,area);
                    }else{
                        data.add(area);
                    }

                }else{
                    tempList.add(area);
                }
            }

            data.addAll(tempList);

            result.setResultData(data);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *时区列表显示
     */
    public ResultBean<Object> globalTimeZone(String accessToken) {
        LOG.info("CompanyMessageService globalTimeZone accessToken={}", accessToken);
        ResultBean<Object> result = new ResultBean<>();
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            Optional<Department> existCompanyOptional = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existCompanyOptional == null) {
                return ResultBean.failedResultWithMsg("企业信息不存在或已删除");
            }
            Iterable<GlobalTimeZone> globalTimeZones = globalTimeZoneRepository.findAll();
            result.setResultData(globalTimeZones);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     *企业时区保存
     */
    public ResultBean<Object> setSysTimeZoneArea(String accessToken, CompanyAreaTimeZoneVO companyAreaTimeZoneVO) {
        LOG.info("CompanyMessageService setSysTimeZoneArea accessToken={},companyAreaTimeZoneVO={}", accessToken, companyAreaTimeZoneVO);
        ResultBean<Object> result = new ResultBean<>();
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            Optional<Department> existCompanyOptional = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existCompanyOptional == null) {
                return ResultBean.failedResultWithMsg("企业信息不存在或已删除");
            }
            if (companyAreaTimeZoneVO == null) {
                result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10004.getErrorMsg());
                return result;
            }
            if (companyAreaTimeZoneVO.getAreaId() == null) {
                result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10004.getErrorMsg());
                return result;
            }
            if (companyAreaTimeZoneVO.getTimeZoneId() == null) {
                result.setCode(StatusCode.ERROR_CODE_10004.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_10004.getErrorMsg());
                return result;
            }
            Optional<GlobalArea> existGlobalArea = globalAreaRepository.findById(companyAreaTimeZoneVO.getAreaId());
            if (existGlobalArea == null) {
                return ResultBean.failedResultWithMsg("地区信息不存在或已删除");
            }
            Optional<GlobalTimeZone> existGlobalTimeZone = globalTimeZoneRepository.findById(companyAreaTimeZoneVO.getTimeZoneId());
            if (existGlobalTimeZone == null) {
                return ResultBean.failedResultWithMsg("时区信息不存在或已删除");
            }
            //判断企业是否设置时区
            DepartmentTimeZone existOrgIdAndTimeZoneId = departmentTimeZoneRepository.findByOrgId(tokenRedisVo.getEnterpriseId());
            DepartmentTimeZone departmentTimeZone = new DepartmentTimeZone();
            if (existOrgIdAndTimeZoneId != null) {
                departmentTimeZone.setId(existOrgIdAndTimeZoneId.getId());
            }
            departmentTimeZone.setTimeZoneId(companyAreaTimeZoneVO.getTimeZoneId());
            departmentTimeZone.setOrgId(tokenRedisVo.getEnterpriseId());
            departmentTimeZoneRepository.save(departmentTimeZone);
            //判断企业是否设置地区
            DepartmentArea existOrgIdArea = departmentAreaRepository.findByOrgId(tokenRedisVo.getEnterpriseId());
            DepartmentArea departmentArea = new DepartmentArea();
            if (existOrgIdArea != null) {
                departmentArea.setId(existOrgIdArea.getId());
            }
            departmentArea.setAreaId(companyAreaTimeZoneVO.getAreaId());
            departmentArea.setOrgId(tokenRedisVo.getEnterpriseId());
            departmentAreaRepository.save(departmentArea);
            //设置到系统参数表中
            SystemParam areaSystemParam = new SystemParam();
            areaSystemParam.setParamName("GlobalArea");
            areaSystemParam.setParamValue(existGlobalArea.get().getName());
            areaSystemParam.setDescription("区域系统参数");
            systemParamService.save(areaSystemParam);
            SystemParam timeZoneSystemParam = new SystemParam();
            timeZoneSystemParam.setParamName("GlobalTimeZone");
            timeZoneSystemParam.setParamValue(existGlobalTimeZone.get().getValue());
            timeZoneSystemParam.setDescription("时区系统参数");
            systemParamService.save(timeZoneSystemParam);
            systemParamService.synch();
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }
    /*
     *获取当前企业地区时区信息
     */
    public ResultBean<Object> presentCompanyAreaAndTimeZoneInfo(String accessToken) {
        LOG.info("CompanyMessageService presentCompanyAreaAndTimeZoneInfo accessToken={}", accessToken);
        ResultBean<Object> result = new ResultBean<>();
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }
            Optional<Department> existCompanyOptional = departmentRepository.findById(tokenRedisVo.getEnterpriseId());
            if (existCompanyOptional == null) {
                return ResultBean.failedResultWithMsg("企业信息不存在或已删除");
            }
            DepartmentTimeZone timeZone = departmentTimeZoneRepository.findByOrgId(tokenRedisVo.getEnterpriseId());
            DepartmentArea area = departmentAreaRepository.findByOrgId(tokenRedisVo.getEnterpriseId());
            CompanyAreaTimeZoneVO companyAreaTimeZoneVO=new CompanyAreaTimeZoneVO();
            if(timeZone != null){
                companyAreaTimeZoneVO.setTimeZoneId(timeZone.getTimeZoneId());
            }
            if(area != null) {
                companyAreaTimeZoneVO.setAreaId(area.getAreaId());
            }
            result.setResultData(companyAreaTimeZoneVO);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }


}
